package com.cskaoyan.util;

import com.cskaoyan.bean.common.BaseRespVo;
import lombok.SneakyThrows;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author stone
 * @date 2023/03/31 17:09
 */
public class DispatchUtil {

    @SneakyThrows
    public static void dispatch(HttpServletRequest request, HttpServletResponse response, HttpServlet instance) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        String requestURI = request.getRequestURI();
        String operation = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        //dispatch(operation,request,response,userServlet);
        Method method = instance.getClass().getDeclaredMethod(operation,HttpServletRequest.class,HttpServletResponse.class);
        method.setAccessible(true);
        Object invoke = method.invoke(instance, new Object[]{request, response});
        if (invoke != null && invoke instanceof BaseRespVo) {
            ResponseUtil.responseJson(response, (BaseRespVo) invoke);
        }
    }
}
